<template>
  <div class="box">
    <div class="head-search">
      <search @onSubmit="onSearch">
        <el-form-item>
          <el-input placeholder="请输入内容" clearable v-model="searchData.val" size="small" class="input-with-select">
            <el-select v-model="searchData.select" clearable slot="prepend" placeholder="请选择">
              <el-option label="借阅人" value="borrowingName"></el-option>
              <!--<el-option label="借阅状态" value="borrowingStatus"></el-option>
              <el-option label="借阅开始时间" value="startTime"></el-option>
              <el-option label="归还时间" value="2"></el-option>-->
            </el-select>
          </el-input>
        </el-form-item>
      </search>
    </div>
    <section class="fun-btn">
      <el-button class="btn" icon="el-icon-plus" type="primary" size="mini" @click="handleAddEdit('add')">登记</el-button>
      <el-button :loading="downloadLoading" icon="el-icon-download" class="btn" type="primary" size="mini"
                 @click="handleDownload">借阅记录下载
      </el-button>
      <!--      <el-button class="btn" type="primary" size="mini">设置</el-button>-->
    </section>

    <section class="list-box">
      <el-table
        :data="tableData"
        border
        v-loading="tableLoading"
        height="calc(100vh - 232px)"
        class="table">
        <el-table-column
          fixed="left"
          align="center"
          type="selection"
          width="60">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="borrowingTime"
          align="center"
          :formatter="formatDate"
          label="借阅开始时间"
          width="180">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          align="center"
          prop="borrowingDay"
          label="借阅天数"
          width="180">
        </el-table-column>
        <!--<el-table-column
          show-overflow-tooltip
          prop="borrowingName"
          align="center"
          label="借阅人">
        </el-table-column>-->
        <el-table-column
          show-overflow-tooltip
          prop="borrowingStatus"
          label="借阅状态"
          align="center"
          width="150">
          <template slot-scope="scope">
            <span style="color: red" v-if="showBorrowingStatus(scope.row) ==='已超期' ">已超期</span>
            <span v-else>{{ showBorrowingStatus(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="remarks"
          label="描述"
          width="300">
        </el-table-column>
        <el-table-column
          fixed="right"
          align="center"
          label="操作"
          width="180">
          <template slot-scope="scope">
            <el-button v-if="scope.row.borrowingStatus === null" @click="handleReturn(scope.row)" type="text">归还
            </el-button>
            <el-button icon="el-icon-edit" type="text" @click="handleAddEdit('edit', scope.row)">编辑</el-button>
            <el-button icon="el-icon-delete" @click="handleDel(scope.row)" type="text" style="color: #F56C6C">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="Number(page.total)>0"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[20, 40, 60, 80]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="Number(page.total)">
      </el-pagination>
    </section>

    <el-drawer
      :title="setDrawer.title"
      :size="setDrawer.size"
      :direction="setDrawer.direction"
      :visible.sync="drawer"
      :before-close="handleBeforeClose"
    >
      <add-p-b-register v-if="type==='add'"
                        ref="addTem"
                        :active="active"
                        :loading="loading"
                        @handleComplete="handleComplete"></add-p-b-register>

      <edit-p-b-register v-if="type==='edit'"
                         v-loading="editLoading"
                         :editObj="editObj"
                         :idContinue="idContinue"
                         @handleSuccess="handleEditSuccess"></edit-p-b-register>

    </el-drawer>

  </div>
</template>

<script>

import Search from '../../../../components/search/search'
import AddPBRegister from './components/addPBRegister'
import EditPBRegister from './components/editPBRegister'
import {
  addBorrowt,
  borrowtDownload,
  detBorrowt,
  getBorrowList, getSingleData,
  revertRequest
} from '../../../../api/house/paperBorrow'
import { dateDiff, formateDate, getToday } from '../../../../util/util'

export default {
  name: 'index', // 纸质档案借阅
  components: {
    EditPBRegister,
    AddPBRegister,
    Search
  },
  // 温湿度管理
  data () {
    return {
      downloadLoading: false,
      tableLoading: false,
      loading: false,
      editLoading: false,
      page: {
        pageNo: 1,
        pageSize: 20,
        total: 0
      },
      tableData: [],
      type: '',
      active: 1,
      searchData: {
        select: 'borrowingName',
        val: ''
      },
      params: [], // 筛选条件
      drawer: false, // 新增
      setDrawer: {
        title: '新增',
        size: '80%',
        direction: 'rtl'
      },
      editObj: {}, // 编辑时数据
      rowData: {}, // 条目数据
      idContinue: ''
    }
  },
  mounted () {
    this.getList()
  },
  methods: {
    showBorrowingStatus (row) {
      let text = ''
      if (row.borrowingStatus !== null) {
        text = '已归还'
      } else {
        const day = dateDiff(getToday(), formateDate(row.borrowingTime))
        if (Number(day) > Number(row.borrowingDay)) {
          text = '已超期'
        } else {
          text = '已借出'
        }
      }
      return text
    },
    getList () {
      this.tableLoading = true
      const param = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize
      }
      if (this.params.length > 0) {
        param.params = this.params
      }
      getBorrowList(param).then(res => {
        this.tableData = res.data.data.list
        this.page.total = res.data.data.total
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.page.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.page.pageNo = val
      this.getList()
    },
    onSearch () {
      // 搜索
      this.params = []
      if (this.searchData.val) {
        this.params = [{
          name: this.searchData.select,
          op: 'like',
          value: this.searchData.val
        }]
      }

      this.getList()
    },
    handleDownload () {
      // 下载
      this.downloadLoading = true
      borrowtDownload().then(res => {
        // this.$message.success('销毁清册操作成功！')
        this.download(res.data)
        this.downloadLoading = false
      }).catch(() => {
        this.downloadLoading = false
      })
    },
    download (data) {
      const blob = new Blob([data])
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob) // 创建下载的链接
      downloadElement.href = href
      downloadElement.target = '_blank'
      downloadElement.download = '借阅记录.xls' // 下载后文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() // 点击下载
      document.body.removeChild(downloadElement) // 下载完成移除元素
      window.URL.revokeObjectURL(href) // 释放掉blob对象
    },
    async handleAddEdit (type, row) {
      // 登记、编辑、
      this.editLoading = true
      if (type === 'edit') {
        this.rowData = row
        this.idContinue = row.idContinue
        getSingleData({ idContinue: row.idContinue }).then(res => {
          this.editObj = {
            pab: {
              borrowingTime: row.borrowingTime,
              returnDate: row.returnDate,
              borrowingDay: row.borrowingDay,
              lendingInstitutions: row.lendingInstitutions,
              rfBorrowing: row.rfBorrowing,
              remarks: row.remarks
            },
            jyrpab: res.data.data.peopleVO,
            jywppab: res.data.data.continueVO,
            zltjpab: res.data.data.fileVO
          }
          this.editLoading = false
        })
      }
      this.drawer = true
      this.setDrawer.title = type === 'add' ? '登记' : '编辑'
      this.type = type
      this.active = 1
    },
    handleEditSuccess (type) {
      // 修改成功
      if (type === 'edit' || type === 'del') {
        this.handleAddEdit('edit', this.rowData)
      }
      this.getList()
    },
    handleBeforeClose (done) {
      // 关闭弹窗初始化
      if (this.type === 'add') {
        this.$refs.addTem.handleEmpty()
      }
      done()
    },
    handleComplete (val) {
      // 提交资料，完成，关闭弹窗
      this.loading = true
      addBorrowt(val).then(res => {
        this.drawer = false
        this.loading = false
        this.$refs.addTem.handleEmpty()
        this.getList()
      }).catch(() => {
        this.loading = false
      })
    },
    handleReturn (row) {
      // 归还
      revertRequest({ id: row.id }).then(res => {
        this.$message.success('归还操作成功！')
        this.getList()
      })
    },
    handleDel (row) {
      // 删除
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        detBorrowt([row.id]).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        })
      }).catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
